package com.chat.controller;

import com.chat.bean.Code;
import com.chat.bean.Login;
import com.chat.bean.Register;
import com.chat.service.LoginService;
import com.chat.util.Md5Util;
import com.chat.util.exception.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
public class LoginCtrl {
    @Autowired
    LoginService loginService;
    @GetMapping("/")
    public String tologin(){
        return "user/register";
    }
    @GetMapping("/user/login")
    public String userlogin(){
        return "user/login";
    }
    /**
     * 登陆
     * */
    @PostMapping("/justlogin")
    @ResponseBody
    public R login(@RequestBody Login login, HttpSession session){
        login.setPassword(Md5Util.StringInMd5(login.getPassword()));
        String userid = loginService.justLogin(login);
        if(userid==null){
            return R.error().message("账号或者密码错误");
        }
        session.setAttribute("userid",userid);
        return R.ok().message("登录成功");
    }
    @PostMapping("/register")
    @ResponseBody
    public R register(@RequestBody Register register, HttpSession session){
        Code code =  new Code();
        code.setCode(register.getCode());
        code.setPhone(register.getPhone());
        Login login = new Login();
        login.setUserid(register.getPhone());
        login.setUsername(register.getUsername());
        login.setPassword(Md5Util.StringInMd5(register.getPassword()));
        int flag = loginService.saveLogin(login);

        String result = loginService.getCode(code.getPhone());
        if(StringUtils.equals(result,code.getCode()) && flag>0){
            return R.ok().message("注册成功,请登录");
        }else{
            return R.error().message("注册失败");
        }



    }
    @GetMapping("/getCode")
    @ResponseBody
    public R register(@RequestParam String phone) {
        String result = loginService.getCode(phone);
        if(StringUtils.isNotEmpty(result)){
            return R.error().message("该手机号已经被注册");
        }
        String code = "123";
        Code code1= new Code();
        code1.setCode(code);
        code1.setPhone(phone);
        loginService.saveCode(code1);
        return R.ok().message("发送成功，稍等");

    }
}
